package com.campus.shop.fiter.web;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.campus.shop.common.Errors;
import com.campus.shop.controller.web.BaseWebController;
import com.campus.shop.entity.User;
import com.campus.shop.exception.ServiceException;
import com.campus.shop.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:拦截器拦截token
 * @Author: xr
 * @Date: 2023/3/30 9:24
 */
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    /**
     * 前处理(该方法在控制器方法前执行)
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("web-token");
        //方法上
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (StringUtils.isBlank(token)) {
            throw new ServiceException(Errors.TOKEN_NOT_EXIT);
        }
        // 获取 token 中的 userid
        String stuId;
        try {
            stuId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException(Errors.TOKEN_INVALID);
        }
        //查询用户
        User user = userService.getById(stuId);
        if (user == null) {
            throw new ServiceException(Errors.TOKEN_USER_ERROR);
        }
        // 密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getTelephone())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(Errors.TOKEN_INVALID);
        }
        BaseWebController.setUser(user.getUserName(), String.valueOf(user.getId()));
        return true;
    }

}
